<template>
    <div class="mod-prod">
        <avue-crud
            ref="crud"
            :data="dataList"
            :option="tableOption"
            :page="page"
            :permission="permission"
            :table-loading="dataListLoading"
            @search-change="searchChange"
            @selection-change="selectionChange"
            @refresh-change="refreshChange"
            @on-load="getDataList"
        >
            <template slot="menuLeft">
                <el-button icon="el-icon-plus"
                           size="small"
                           type="primary"
                           @click.stop="genoppo()">
                    生成商机
                </el-button>
            </template>

            <template slot="menu" slot-scope="scope">
                <el-button
                    icon="el-icon-edit"
                    size="small"
                    type="primary"
                    @click="addOrUpdateHandle(scope.row)">
                    修改
                </el-button>
                <el-button
                    icon="el-icon-delete"
                    size="small"
                    type="danger"
                    @click="deleteHandle(scope.row.id)">
                    删除
                </el-button>
                <el-button
                    icon="el-icon-menu"
                    size="small"
                    type="info"
                    @click="detailHandle(scope.row.custCode)">
                    详情
                </el-button>
            </template>
        </avue-crud>

        <cust-detail ref="custDetailRef"></cust-detail>

        <!-- 新增/修改组件 -->
        <add-or-update
            v-if="addOrUpdateVisible"
            ref="addOrUpdate"
            @refreshDataList="refreshChange">
        </add-or-update>
    </div>
</template>

<script>
import { tableOption } from '@/crud/customer/custList'
import AddOrUpdate from '@/views/modules/customer/cust-update.vue'
import CustDetail from "@/views/templates/custDetail.vue";

export default {
    components: { AddOrUpdate, CustDetail },
    data() {
        return {
            dataForm: {
                prodName: ''
            },
            permission: {
                delBtn: this.isAuth('prod:prod:delete')
            },
            dataList: [],
            page: {
                total: 0,
                currentPage: 1,
                pageSize: 10, // 👈 改为合理分页
                pageSizes: [10, 20, 50]
            },
            addOrUpdateVisible: false,
            dataListSelections: [],
            dataListLoading: false,
            tableOption: tableOption,
            resourcesUrl: process.env.VUE_APP_RESOURCES_URL,

            // 详情弹窗相关
            detailVisible: false,
            detailData: null
        }
    },
    mounted() {
        this.initData()
    },
    methods: {
        initData() {
            // 初始化字典：行业、等级等（保持不变）
            Promise.all([
                this.$http({
                    url: this.$http.adornUrl('/crm/base/cusIndustry/page'),
                    method: 'get',
                    params: this.$http.adornParams({ current: 1, size: 99 })
                }),
                this.$http({
                    url: this.$http.adornUrl('/crm/base/custLevel/page'),
                    method: 'get',
                    params: this.$http.adornParams({ current: 1, size: 99 })
                })
            ]).then(([industryRes, levelRes]) => {
                const industryCol = this.tableOption.column.find(i => i.prop === 'custType');
                if (industryCol) {
                    industryCol.dicData = industryRes.data.obj.records.map(i => ({
                        label: i.industryName,
                        value: i.industryName
                    }));
                }

                const levelCol = this.tableOption.column.find(i => i.prop === 'dbiz2');
                if (levelCol) {
                    levelCol.dicData = levelRes.data.obj.records.map(i => ({
                        label: i.levelCode,
                        value: i.levelCode
                    }));
                }
            });
        },

        genoppo() {
            // 注意：原 genoppo 方法逻辑似乎不完整，这里保留但不调用分页参数
            this.$message.info('生成商机功能待完善');
        },

        getDataList(page, params, done) {
            this.dataListLoading = true;
            const currentPage = page?.currentPage || this.page.currentPage;
            const pageSize = page?.pageSize || this.page.pageSize;

            this.$http({
                url: this.$http.adornUrl('/crm/base/cust/page'),
                method: 'get',
                params: this.$http.adornParams({
                    current: currentPage,
                    size: pageSize,
                    ...params
                })
            }).then(({ data }) => {
                const result = data.obj || {};
                this.dataList = result.records || [];
                this.page.total = result.total || 0;
                this.dataListLoading = false;
                if (done) done();
            }).catch(() => {
                this.dataList = [];
                this.page.total = 0;
                this.dataListLoading = false;
                if (done) done();
            });
        },

        addOrUpdateHandle(row) {
            this.addOrUpdateVisible = true;
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(row);
            });
        },

        // 👇 新增：详情弹窗
        detailHandle(custCode) {
            this.$refs.custDetailRef.show(custCode)
        },

        deleteHandle(id) {
            this.$confirm(`确定删除该客户？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl(`/crm/base/cust/${id}`),
                    method: 'delete',
                    data: this.$http.adornData({ id }, false)
                }).then(() => {
                    this.$message.success('删除成功');
                    this.refreshChange();
                });
            }).catch(() => {});
        },

        searchChange(params, done) {
            this.page.currentPage = 1;
            this.getDataList(this.page, params, done);
        },

        selectionChange(val) {
            this.dataListSelections = val;
        },

        refreshChange() {
            this.getDataList(this.page);
        }
    }
}
</script>

<style scoped>
/* 可选：调整弹窗内表格间距 */
.el-descriptions {
    margin-bottom: 20px;
}
</style>
